package cn.echo.ecc.service.impl;

import cn.echo.ecc.domain.Blacklist;
import cn.echo.ecc.domain.MessageSms;
import cn.echo.ecc.dto.BlockDto;
import cn.echo.ecc.enums.GlobalExceptionCode;
import cn.echo.ecc.mapper.MessageSmsMapper;
import cn.echo.ecc.service.IBlacklistService;
import cn.echo.ecc.service.IMessageSmsService;
import cn.echo.ecc.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hulan
 * @since 2022-09-24
 */
@Service
public class MessageSmsServiceImpl extends ServiceImpl<MessageSmsMapper, MessageSms> implements IMessageSmsService {

    @Autowired
    private IBlacklistService blacklistService;

    /**
     * 拉黑
     * @param blockDto
     */
    @Override
    public void block(BlockDto blockDto) {
        AssertUtil.isNotNull(blockDto, GlobalExceptionCode.PARAM_IS_NOT_BULL);
        String phone = blockDto.getPhone();
        Blacklist blacklist = getBlacklist(phone);
        AssertUtil.isNull(blacklist, GlobalExceptionCode.BLACKLIST_EXISTED_ERROR);
        addBlacklist(phone,blockDto.getUserId(),blockDto.getIp(),blockDto.getReason());
    }

    private void addBlacklist(String phone, Long userId, String ip, String reason) {
        Blacklist blacklist = new Blacklist();
        blacklist.setIp(ip);
        blacklist.setPhone(phone);
        blacklist.setUserId(userId);
        blacklist.setCreateTime(new Date());
        blacklist.setReason(reason);
        blacklistService.insert(blacklist);
    }

    private Blacklist getBlacklist(String phone) {
        Wrapper<Blacklist> wrapper = new EntityWrapper<>();
        wrapper.eq("phone",phone);
        return blacklistService.selectOne(wrapper);
    }
}
